<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;
use Qiniu\Auth;
use OSS\OssClient;
use OSS\Core\OssException;
class  Base extends Controller {
    protected $_error;
    protected $_header;//用户的请求头信息
    protected $otherLogin  = '您的账号已在其他设备登录';
    protected $frost = '您的账号已被冻结';
    protected $del = '您的账号已被删除';
    // 构造函数
    public function _initialize(){
        // 如果配置项为空 则直接返回

    }

    /**
     * 验证唯一——单点登录
     * user_id，time，salt，value
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        if($uid == 0) {
            return 111;
        } else {
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            if($user['user_status'] == 2){ // 冻结
                return 110;
            }
            if($user['user_status'] == 3){ // 删除
                return 1103;
            }
            $token = $user['user_token'];
            $appId = "A2020308310121";
            $appkey = "9PA807B0-BE12-S521-6998-6D57B0CCE8ON";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey) {
                return 112;
            } else {
                return 111;
            }
        }
    }
    /**
     * 获取七牛token
     * @return string
     */
    public function getQiniuToken(){
        require_once ('../extend/qiniu/autoload.php');
        header("Access-Control-Allow-Origin:*");
        $accessKey = config('qiniu')['accessKey'];
        $secretKey = config('qiniu')['secretKey'];
        $bucket = config('qiniu')['bucket'];
//        $auth = new Qiniu();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        return json_encode(array('data'=>$token));
    }
    /**
     * 云之讯发送短信
     * @param $phone
     * @param $num
     * @return mixed
     */
    public function duaxin($phone,$num){
        $SpCode = '230149';
        $LoginName = 'js_px';
        $Password = 'panson58398860';
        $MessageContent = iconv("UTF-8", "gbk//TRANSLIT", "您的验证码为{$num}，请在10分钟内使用！");
        $body = "SpCode=$SpCode&LoginName=$LoginName&Password=$Password&MessageContent=$MessageContent&UserNumber=$phone&SerialNumber=&ScheduleTime=&f=1";
        $header = array(
            'Accept:application/x-www-form-urlencoded',
            'Content-Type: application/x-www-form-urlencoded; charset=gbk'
        );
        $url = 'https://api.ums86.com:9600/sms/Api/Send.do';
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = mb_convert_encoding($result,'UTF-8','GBk');
        $res = explode('&',$result);
        return $res;
    }
    /**
     * param $tmp
     * param $name
     * param $size
     * 上传图片
     */
//    public function uploadFile($tmp,$name,$size)


    /**
     * formatTime 时间格式化
     * @param $time 时间戳
     * @return string
     */
    public function formatTime($time) {
        $now_time = time();
        $t = $now_time - $time;
        $yea = (int) ($t / (86400 * 30 * 12));
        if ($yea >= 1) {
            return $yea.'年前';
        }
        $mon = (int) ($t / (86400 * 30));
        if ($mon >= 1) {
            return '一个月前';
        }
        $day = (int) ($t / 86400);
        if ($day >= 1) {
            return $day . '天前';
        }
        $h = (int) ($t / 3600);
        if ($h >= 1) {
            return $h . '小时前';
        }
        $min = (int)($t / 60);
        if ($min >= 1) {
            return $min . '分钟前';
        }
        return '刚刚';
    }

    /**
     * 获取任意长度的随机字符串
     * @param $length
     * @return string
     */
//    function getRandChar($length)
//    {
//        $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
//            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
//            't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
//            'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
//            'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
//            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
//        $char_txt = '';
//        for ($i = 0; $i < $length; $i++) {
//            $char_txt .= $chars[array_rand($chars)];
//        }
//        return $char_txt;
//    }

    /**
     * 验证码
     * @param $length
     * @return string
     */
    function getCodeChar($length)
    {
        $chars = array(
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
        $char_txt = '';
        for ($i = 0; $i < $length; $i++) {
            $char_txt .= $chars[array_rand($chars)];
        }
        return $char_txt;
    }
    public function getAcount()
    {
        //==========base里放到===============
        $zimu = range('a','z');
        $one = rand(0,25);
        $two = rand(0,25);
        $thr = rand(0,25);
        $four = rand(0,25);
        $zimu2 = $zimu[$one].$zimu[$two].$zimu[$thr].$zimu[$four];
        $num = rand(100000,999999);
        return $zimu2.$num;
        //=========================
    }

    //------------------------mww-------------------------------------------------------

    /**
     * 支付回调处理
     */
    public function alltypespay($num,$back_order_id,$queryId='')
    {
        $today = date('Y-m-d H:i:s');
        $table_good = 'up_self_goods';
        $order = Db::table('up_self_order')->where('order_no',$num)
            ->field('order_id,is_pay,order_contract,total_price,user_id,order_id')->find();
        if($order['order_contract'] != 1){
            $table_good = 'up_goods';
        }
        if($order['is_pay'] == 0){
            Db::startTrans();
            try{
                //改订单状态
                $update = [
                    'is_pay' => 1,
                    'order_back_order_id' => $back_order_id,
                    'order_query_id' => $queryId,
                    'pay_time' => $today,
                ];
                Db::table('up_self_order')->where('order_no',$num)->update($update);
                //加商品销量
                $field = 'goods_id,num,attr_id,erp_ak';
                $details = Db::table('up_self_order_detail')->where('order_id',$order['order_id'])->field($field)->select();
                foreach ($details as $k=>$v){
                    Db::table($table_good)->where('good_id',$v['goods_id'])->setInc('good_sales',$v['num']);
                }
                Db::commit();
                //平台收入
                allInRevenue(1,$order['total_price'],$order['user_id'],$order['order_contract'],$order['order_id']);
                //支付成功通知：
                $title = '下单成功';
                $content = '下单成功，友情提醒：快递发出15天内未收到货物，请及时联系我司客服，核实订单情况；快递发出超过20天未收到货物，也未与我司客服联系，我司将无法处理。';
                allInNotice($title,$content,2,$order['user_id'],$order['order_id'],$order['order_contract']);
                try{
                    $this->Jpush(1, $order['user_id'], '下单成功', ['n_id' => $order['order_id'],'type' => $order['order_contract'],'n_type' => 2]);
                }catch(\Exception $e){
                }
                return true;
            }catch (\Exception $e) {
                Db::rollback();
                return false;
            }
        }else{
            return false;
        }
    }
    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        if(is_string($alias) || is_int($alias)){
            $alias = (string)$alias;
        }
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush.appKey'),config('jpush.masterSecret'));
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        $push->message($message, [
//            'title' => 'Hello',
            'content_type' => 'text',
            'extras' => $extras
        ]);
        return $push->send();
    }
    /**
     * 根据user_id获取当前绑定的学生信息
     * @param $user_id
     * @return array
     */
    protected function getSonByUser($user_id)
    {
        $res = [
            'status' => 0,
            'msg' => '没有选择学生，请先选择学生'
        ];
        $sonid = Db::table('up_u_user')->where('user_id',$user_id)->value('user_son_id');
        if($sonid){
            $data = Db::table('up_u_user_son')->where('uson_id',$sonid)
                ->field('uson_id,uson_username,user_gender,uson_year,uson_school,uson_idcard,uson_size')
                ->find();
            if($data){
                $res = [
                    'status' => 200,
                    'msg' => $data
                ];
            }else{
                $res = [
                    'status' => 0,
                    'msg' => '学生选择失效，请重新选择学生进行购买'
                ];
            }

        }
        return $res;
    }

    /**
     * 查看套装下的衣服们
     * @param oc_id
     * @return bool
     */
    public function getTaoGoods($oc_id)
    {
        extract(input());
        $field = 'goods_id,detail_id,order_id,num,unit_price,goods_info';
        $field .= ',good_name,good_thumb';
        $data = Db::table('up_self_order_detail')->alias('sd')
            ->join('up_goods g','sd.goods_id=g.good_id','LEFT')
            ->where('oc_id_erp',$oc_id)
            ->field($field)
            ->select();
        return $data;
    }
    //------------------------mww53-------------------------------------------------------

    public function askFapiao($head,$shui,$phone,$email,$mingxi)
    {
        import('org.DESDZFP', EXTEND_PATH);
        $body_json2 = array(
            'buyername' => $head,
            'taxnum' => $shui,
            'phone' => $phone,
            'address' => '',
            'account' => '',
            'payee' => '',
            'checker' => '',
            'orderno' => time(). rand(100000,999999),
            'invoicedate' => date('Y-m-d H:i:s'),
            'clerk' => '潘汝滨',//开票人
            'saleaccount' => '中国银行南京市南钢支行    523571906927',
            'saletaxnum' => '91320116759496005P',
            'salephone' => '025-58398860',
            'saleaddress' => '南京市沿江工业开发区浦六北路193号 ',
            'kptype' => '1',
            'tsfs' => '2',
            'email' => $email,
            'detail' => $mingxi
        );
        $body_json = array(
            'identity' => '35D31288192AFCA85722962CC6FF9BAD42C99E76F72CC964',
            'order' => $body_json2
        );
        $body = json_encode($body_json);
        $des = new \DESDZFP;
        $body = $des->encrypt($body);
        $body_json = array(
            'order' => $body
        );
        $url = 'https://nnfp.jss.com.cn/shop/buyer/allow/cxfKp/cxfServerKpOrderSync.action';
        $res = $this->curl_post($url,$body_json);
//        dump($res);die;
        if($res['status'] == '0000'){
            return ['status' => 200,'msg' => $res['fpqqlsh']];
        }else{
            return ['status' => 100,'msg' => '开票失败'];
        }
    }
    public function getFapiaoRes()
    {
        $fpqqlsh = '20041418322101105088';
        $fpqqlsh = '20041418413401105135';
        import('org.DESDZFP', EXTEND_PATH);
        $body_json = array(
            'identity' => '2329CC5F90EDAA8208F1F3C72A0CE72A713A9D425CD50CDE',
            'fpqqlsh' => $fpqqlsh
        );
        $body = json_encode($body_json);
        $des = new \DESDZFP;
        $body = $des->encrypt($body);
        $body_json = array(
            'order' => $body
        );
        $url = 'https://nnfpbox.nuonuocs.cn/shop/buyer/allow/ecOd/queryElectricKp.action';
        $res = $this->curl_post($url,$body_json);
        if($res['result'] == 'success' && $res['list'][0]['c_status'] == 2){
            //TODO:改用户地址(开完票会自动发送到邮箱，所以可以不用管)
            $pdf = $res['list'][0]['c_url'];
            $img = $res['list'][0]['c_jpg_url'];
            return ['status' => 200,'msg' => '开票成功'];
        }else{
            return ['status' => 100,'msg' => '开票失败'];
        }
    }
    public function curl_post($url , $data=array()){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        // POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
        // 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

    //-------------------------------------------erp---------------------------------------------

}